package com.example.demo.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class JWTUtil {
    private static final String SIGN = "!@#$%--Big.Hu--456789";

    /**
     * 生成token：header.payload.sign
     *
     * @param openid 登陆信息，如：{"username":"张三"}
     * @return token
     */
    public static String getToken(String openid) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 7); // 过期时间：7天
        JWTCreator.Builder builder = JWT.create();
        //builder.withClaim("userid",user.getStudentId());
        //builder.withClaim("userEmial",user.getDevEmail());
        builder.withClaim("openid", openid);
        Map<String, Object> header = new HashMap<>();
        header.put("typ", "JWT");
        header.put("alg", "HMAC256");
        String token = builder.withHeader(header)
                .withExpiresAt(calendar.getTime())
                .sign(Algorithm.HMAC256(SIGN));
        return token;
    }

    public static String getToken2(String openid) {
        String timestamp = String.valueOf(System.currentTimeMillis());
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 360); // 过期时间：7天
        JWTCreator.Builder builder = JWT.create();
        //builder.withClaim("userid",user.getStudentId());
        //builder.withClaim("userEmial",user.getDevEmail());
        builder.withClaim("openid", openid + timestamp);
        Map<String, Object> header = new HashMap<>();
        header.put("typ", "JWT");
        header.put("alg", "HMAC256");
        String token = builder.withHeader(header)
                .withExpiresAt(calendar.getTime())
                .sign(Algorithm.HMAC256(SIGN));
        return token;
    }


    public static long verify(String token) {
        JWTVerifier build = JWT.require(Algorithm.HMAC256(SIGN)).build();
        DecodedJWT decodedJwt = build.verify(token);
        Map<String, Claim> claims = decodedJwt.getClaims();
        return decodedJwt.getClaim("userId").asLong();
    }
}
